<template>
  <u-form-item
    :label="label"
    :prop="props.data.field"
    :required="props.data.required"
    :rules="props.data.rules"
  >
		<u-upload
				:fileList="fileList"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				multiple
				:maxCount="10"
			></u-upload>
	</u-form-item>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useProps } from '../hooks/props'

const props = defineProps<{ data: Record<string, any>; form: Record<string, any> }>()
const emits = defineEmits(['valueChange'])

const { label } = useProps(props)

const fileList = ref([]);

const afterRead = async (event) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = fileList.value.length;
  lists.map((item) => {
    fileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url);
    let item = fileList.value[fileListLen];
    fileList.value.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: result,
    });
    fileListLen++;
  }
}

const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
      filePath: url,
      name: 'file',
      formData: {
        user: 'test',
      },
      success: (res) => {
        setTimeout(() => {
          resolve(res.data.data);
        }, 1000);
      },
    });
  });
};

const onChange = (index: any) => {
	emits('valueChange', { name: props.data.field, value: props.data.options[index] } )
}

const deletePic = () => {
	
}
</script>

<style lang="scss" scoped></style>
